package com.sumu.today.models.permission.controller;


import com.sumu.today.models.permission.entity.User;
import com.sumu.today.models.permission.service.UserService;
import com.sumu.today.models.permission.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sumu
 * @since 2021-12-15
 */
@RestController
@RequestMapping("/permission/user")
public class UserController {

    @Autowired
    UserService userService;


    @GetMapping("/register")
    public ModelAndView toRegister(ModelAndView modelAndView) {
        modelAndView.setViewName("permission/user/register");
        return modelAndView;
    }

    @PostMapping("/register")
    public ModelAndView registerUser(ModelAndView modelAndView, @Validated User user,
                                     BindingResult bindingResult, HttpServletRequest request) {

        if (bindingResult.hasErrors()) {
            modelAndView.addObject("error", bindingResult.getFieldError().getDefaultMessage());
            modelAndView.setViewName("permission/user/register");
            return modelAndView;
        }

        boolean register = userService.register(user, request);
        if (register) {
            modelAndView.addObject("msg", "register and login success !!!");
            modelAndView.setViewName("index");
            return modelAndView;
        } else {
            modelAndView.addObject("error", "register failed !!!");
            modelAndView.setViewName("permission/user/register");
            return modelAndView;
        }
    }
}
